<template>
	<div>
		<comTop :title="$route.meta.title"></comTop>
		<!-- <div class="tag">
			<p class="active">便携健康体检设备</p>
			<p>智能查询终端</p>
		</div> -->

		<div class="tool">
			<p>
				<span style="color: #000;">
					当前老人：xxx
				</span>
			</p>
			<p style="margin-right: 10px;float: right;" v-if="!ifadd">
				<el-button
					style="background-color:  rgba(2, 167, 240, 1);width: 50px;padding: 0;color: #fff;margin-top: 10px;height: 30px;line-height: 10px;"
					size="medium" @click="setwei()">获取</el-button>
				<el-button
					style="background-color:  rgba(2, 167, 240, 1);width: 50px;padding: 0;color: #fff;margin-top: 10px;height: 30px;line-height: 10px;"
					size="medium" @click="Editor">编辑</el-button>
				<el-button
					style="background-color:  rgba(2, 167, 240, 1);color: #fff;margin-top: 10px;height: 30px;line-height: 10px;"
					size="medium" @click="Editored">编辑完成</el-button>
				<el-button
					style="background-color:  rgba(2, 167, 240, 1);color: #fff;margin-top: 10px;height: 30px;line-height: 10px;"
					size="medium" @click="">保存编辑</el-button>

			</p>
			<p style="margin-right: 10px;float: right;" v-else>
				<span style="color: red;font-size: 16px;font-weight: bold;" v-if="!rectxtype">
					请在地图上点击并移动鼠标绘制围栏！
				</span>
				<el-button v-if="rectxtype"
					style="background-color:  rgba(2, 167, 240, 1);color: #fff;margin-top: 10px;height: 30px;line-height: 10px;"
					size="medium" @click="rectx">重绘</el-button>
				<el-button
					style="background-color:  rgba(2, 167, 240, 1);color: #fff;margin-top: 10px;height: 30px;line-height: 10px;"
					size="medium" @click="quxiao">取消</el-button>
				<el-button
					style="background-color:  rgba(2, 167, 240, 1);color: #fff;margin-top: 10px;height: 30px;line-height: 10px;"
					size="medium" @click="queren">确认添加</el-button>
			</p>
		</div>
		<el-dialog v-if="cities.length" :title="'电子围栏'+'('+cities[newweiidx].label+')'" :visible.sync="dialogVisible" width="30%"
			:before-close="handleClose">
			<div style="overflow: hidden;"><span style="float: left;line-height: 30px;">围栏名称：</span>
				<div style="float: left;width: calc(100% - 100px);">
					<el-input placeholder="请输入新的围栏名称" v-model="newweilabel" clearable>
					</el-input>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary"
					@click="dialogVisible = false;cities[newweiidx].label = newweilabel;newwei[newweiidx].label = newweilabel;">
					确定</el-button>
			</span>
		</el-dialog>
		<el-dialog :title="'添加电子围栏'" :visible.sync="dialogVisible1" width="30%" :before-close="handleClose">
			<div style="overflow: hidden;"><span style="float: left;line-height: 30px;">围栏名称：</span>
				<div style="float: left;width: calc(100% - 100px);">
					<el-input placeholder="请输入添加的围栏名称" v-model="newweilabel" clearable>
					</el-input>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible1 = false">取 消</el-button>
				<el-button type="primary" @click="addwei">确定</el-button>
			</span>
		</el-dialog>
		<div class="tableitemss" :style="{height: height+'px'}">
			<!-- 百度地图 -->
			<!-- <baidu-map :center="center" :zoom="zoom" @ready="handler" style="height:100%" @click="getClickInfo"
				:scroll-wheel-zoom='true'>
			</baidu-map> -->
			<!-- 高德地图 -->
			<div id="container1" style="height: 100%;position: relative;">
				<div class="containertool">
					<div style="display: block;overflow: hidden;">
						<div style="float: left;">
							<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAll">
								全选(围栏列)</el-checkbox>
						</div>
						<el-button
							style="border: 0;color:#0040D0; padding: 0;height: 20px;line-height: 20px;margin-left: 15px;float: right;"
							@click="newweilabel = '';dialogVisible1=true;" v-if="!ifadd">添加</el-button>
					</div>
					<div v-for="city,index in cities" id="bosxs">
						<el-checkbox-group v-model="checkedlst" @change="handleChecked">
							<el-checkbox :label="city.id" :key="city.id">{{city.label}}</el-checkbox>
						</el-checkbox-group>
						<p>
							<el-button
								style="border: 0;color: #0040D0; padding: 0;height: 20px;line-height: 20px;margin-left: 15px;"
								@click="getnow(city,index)">定位</el-button>
							<el-button
								style="border: 0;color: #0040D0; padding: 0;height: 20px;line-height: 20px;margin-left: 15px;"
								@click="newweiidx=index;dialogVisible=true;newweilabel = city.label;">编辑标题</el-button>
							<el-button
								style="border: 0;color: red; padding: 0;height: 20px;line-height: 20px;margin-left: 15px;"
								@click="remove(index)">删除</el-button>
						</p>
					</div>
				</div>
			</div>

		</div>
	</div>
</template>

<script>
	export default {
		name: '',
		data() {
			const self = this;
			return {
				height: 0,
				ifadd:false,
				rectxtype:false,
				query: {
					xinghao: 0,
					jigou: 0,
					id: '',
					data: []
				},
				checkedlst: [],
				isIndeterminate: false,
				cities: [{
						id: 1,
						label: '电子围栏1',
						center: [109.45744048529967, 36.49771311230842],
						radius: 3000
					},
					{
						id: 2,
						label: '电子围栏2',
						center: [109.45744048529967, 36.49771311230842],
						radius: 2000
					},
					{
						id: 3,
						label: '电子围栏3',
						center: [109.45744048529967, 36.49771311230842],
						radius: 1000
					}
				],
				checkAll: false,
				zoom: 13,
				map: false,
				dialogVisible: false,
				dialogVisible1: false,
				newweilabel: '',
				infoWindow: {},
				newwei: [],
				newweiidx: 0
			};
		},
		created() {
			this.map && this.map.destroy();
			this.boxcheck(() => {
				setTimeout(() => {
					this.height =  $('.wrapper').height() - document.getElementsByClassName('tableitemss')[0].getBoundingClientRect().top - 10;
				}, 400)
			})
			this.$nextTick(() => {
				try{
					this.map = new AMap.Map('container1', {
						center: [109.95744048529967, 36.49771311230842],
						zoom: this.zoom,
						resizeEnable: true,
						pitch:20,
						viewMode:'3D',
					})
					var roadNetLayer =  new AMap.TileLayer.RoadNet();//网格
					// var satelliteLayer = new AMap.TileLayer.Satellite();//卫星
					this.map.add(roadNetLayer)
					this.newwei = JSON.parse(JSON.stringify(this.cities));
					this.infoWindow = new AMap.InfoWindow({
						offset: new AMap.Pixel(0, -35),
					});
				}catch(e){
					this.$message.error('地图加载错误，请刷新重试!');
				}
				
			})
		},
		components: {},
		computed: {},
		methods: {
			remove(idx) { //删除围栏
				var id = this.cities[idx].id;
				for (var i in this.checkedlst) {
					if (this.checkedlst[i] == id) {
						this.checkedlst.splice(i, 1);
						break;
					}
				};
				this.cities.splice(idx, 1);
				this.setwei();
			},
			addwei() { //添加围栏
				if (!this.newweilabel) {
					return this.$message.error('请输入电子围栏名称!');
				}
				this.ifadd = true;
				this.dialogVisible1 = false;
				var id = this.cities.length + 1;
				var obj = {
					id: id,
					label: this.newweilabel,
					center: [],
					radius: 0
				}
				this.addcircle(obj);
			},
			addcircle(obj){//添加圆
				this.checkAll =false;
				this.checkedlst = [];
				this.setwei(true);
				this.rectxtype = false;
				var mouseTool = new AMap.MouseTool(this.map),_this = this;
				mouseTool.circle({
					strokeColor: "#F33",  //线颜色
					strokeOpacity: 1,  //线透明度
					strokeWeight: 3,  //线粗细度
					fillColor: "#ee2200",  //填充颜色
					fillOpacity: 0.35, //填充透明度
					extData:{
						type:'circle',
						oneid:'circle',
						name:'newcircle'
					}
				})
				mouseTool.on('draw', function(event) {
				  // console.log('覆盖物对象绘制完成',event.obj)
				  _this.rectxtype = true;
				  mouseTool.close()
				})
			},
			rectx(){//重绘
				var circle = this.getover({type:'circle',oneid:'circle',name:'newcircle'});
				this.map.remove(circle)
				this.addcircle()
			},
			quxiao(){//取消添加按钮
				this.ifadd = false;
				this.rectxtype = false;
				var circle = this.getover({type:'circle',oneid:'circle',name:'newcircle'});
				this.map.remove(circle)
			},
			queren(){//确认添加按钮
				var id = this.cities.length + 1;
				var circle = this.getover({type:'circle',oneid:'circle',name:'newcircle'});
				if(!circle.length){
					return this.$message.error('请先在地图上绘制电子围栏!');
				}
				var obj = circle[0].Ce;
				this.cities.push({
					id: id,
					label: this.newweilabel,
					center: [obj.center.lng,obj.center.lat],
					radius: obj.radius
				});
				// console.log(this.cities)
				this.$message.success('围栏已添加');
				this.map.remove(circle);
				this.rectxtype = false;
				this.ifadd = false;
				this.checkedlst = [id];
				this.setwei();
			},
			handleClose(done) {
				done();
			},
			handleChecked(value) {
				let checkedCount = value.length;
				this.checkAll = checkedCount === this.cities.length;
				this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
			},
			handleCheckAll(val) {
				this.checkedlst = [];
				if (val) {
					for (var i in this.cities) {
						var o = this.cities[i]
						this.checkedlst.push(o.id)
					}
				}
				this.isIndeterminate = false;
			},
			getpos(lnglat) { //根据经纬度获取详细信息
				return new Promise((resolve) => {
					AMap.plugin('AMap.Geocoder', function() {
						var geocoder = new AMap.Geocoder({
							// city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode 
							city: '010'
						})
						geocoder.getAddress(lnglat, function(status, result) {
							if (status === 'complete' && result.info === 'OK') {
								// result为对应的地理位置详细信息 
								// console.log(result)
								resolve({
									address: result.regeocode.formattedAddress,obj:result
								});
							}
						})
					})
				});
			},
			getlnglat(str) { //根据纤细地址获取经纬度
				return new Promise((resolve) => {
					AMap.plugin('AMap.Geocoder', function() {
						var geocoder = new AMap.Geocoder({
							// city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode 
							city: '010'
						})
						geocoder.getLocation(str, function(status, result) {
						    if (status === 'complete' && result.info === 'OK') {
						      // result中对应详细地理坐标信息
							  resolve({address:result.geocodes[0].location,obj:result})
						    }
						  })
					})
				});
			},
			setpos(center) {
				this.map.setCenter(center);
				this.map.setZoom(this.zoom);
			},
			isselect(obj) {
				for (var i in this.checkedlst) {
					if (obj.id == this.checkedlst[i]) {
						return true;
					}
				}
			},
			getnow(obj, idx) {
				var type = false;
				var id = obj.id;
				var circle = this.getover({type:'circle',oneid:'circle',id});
				if (!circle.length) {
					return this.$message.error('请先勾选并获取需要定位的电子围栏!');
				}
				this.map.setFitView(circle,false,[100,100,100,100])
			},
			async setwei(isshowmag) { //电子围栏
			// var address = await this.getlnglat('北京市海淀区苏州街')
			// console.log(address)
				if (!this.checkedlst.length && !isshowmag) {
					this.$message.error('暂未勾选需要获取的电子围栏!');
				};
				this.rewei();
				var arr = [];
				this.newwei = JSON.parse(JSON.stringify(this.cities));
				for (let j in this.newwei) {
					var obj = this.newwei[j];
					if (!this.isselect(obj)) {
						continue
					};
					var circle = new AMap.Circle({
						center: new AMap.LngLat(obj.center[0], obj.center[1]),
						radius: obj.radius, //半径
						strokeColor: "#F33",  //线颜色
						strokeOpacity: 1,  //线透明度
						strokeWeight: 3,  //线粗细度
						fillColor: "#ee2200",  //填充颜色
						fillOpacity: 0.35, //填充透明度
						extData:{
							type:'circle',
							oneid:'circle',
							...obj
						}
					})
					arr.push(circle);
					// this.setpos(obj.center);
					obj.circleEditor = new AMap.CircleEditor(this.map, circle);

					let marker = new AMap.Marker({
						position: obj.center,
						map: this.map,
						title: obj.label,
						extData:{
							type:'marker',
							oneid:'circle',
							...obj
						}
					});
					obj.circleEditor.on('move', function(event) {
						let obj = event.target.Ce;
						marker.setPosition([obj.center.lng, obj.center.lat])
					})
					obj.circleEditor.on('adjust', function(event) {})
					obj.circleEditor.on('end', (event) => {
						let objs = event.target.Ce;
						obj.center[0] = objs.center.lng;
						obj.center[1] = objs.center.lat;
						obj.radius = objs.radius;
					})
					marker.setLabel({
						offset: new AMap.Pixel(5, 0), //设置文本标注偏移量
						content: "<div class='info'>我是围栏" + obj.label + "</div>", //设置文本标注内容
						direction: 'right' //设置文本标注方位
					});
					let info = [];
					let address = await this.getpos(obj.center);
					info.push(
						"<div style=\"padding:2px 0px 0px 0px;\"><h4 style='padding-bottom:5px;font-size:16px'>当前围栏信息</h4>"
						);
					info.push("<p class='input-item'>名称 : " + obj.label + "</p>");
					info.push("<p class='input-item'>区域半径 : " + obj.radius + "米</p>");
					info.push("<p class='input-item'>中心位置 : " + address.address + "</p></div></div>");
					marker.on('click', (e) => {
						this.infoWindow.setContent(info.join(""));
						this.infoWindow.open(this.map, e.target.getPosition());
					})
					this.map.add(circle);
					this.map.add(marker);
				}
				this.map.setFitView(arr,false,[100,100,100,100])
			},
			rewei() { //删除电子围栏
				var circle = this.getover({type:'circle',oneid:'circle'});
				this.Editored();
				var marker = this.getover({type:'marker',oneid:'circle'});
				this.map.remove(circle);
				this.map.remove(marker);
				this.infoWindow.close();
			},
			clearall(){//清空地图所有覆盖物
				this.map.clearMap();
			},
			getover(obj){//获取覆盖物
				var overlays = this.map.getAllOverlays();
				var arr = [];
				function istrue(o){
					var ty = true;
					for(var j in obj){
						var d = obj[j];
						if(o[j] != obj[j]){
							ty = false;
							break;
						}
					}
					return ty;
				}
				if(!obj){
					arr = overlays;
				}else{
					for(var i in overlays){
						var o = overlays[i];
						var data = o.getExtData();//extData
						if(istrue(data)){
							arr.push(o);
						}
					}
				}
				// console.log(arr,obj)
				return arr;
			},
			Editor() { //编辑电子围栏
				for (var i in this.newwei) {
					if(!this.newwei[i].circleEditor) continue;
					this.newwei[i].circleEditor.open()
				}
			},
			Editored() { //编辑电子围栏完成
				for (var i in this.newwei) {
					if(!this.newwei[i].circleEditor) continue;
					this.newwei[i].circleEditor.close()
				}
			},
			getdata() {

			},
			save() {
			}
		},
		watch: {
			collapses() {}
		},
		destroyed() {
			// console.log('closre')
			this.clearall();
			this.map && this.map.destroy();
		},
		mounted() {
		}
	};
</script>
<style type="text/css">
	.amap-marker-label {
		border: 0;
	}

	.info {
		position: relative;
		top: 0;
		right: 0;
		min-width: 0;
	}

	.el-dialog--center {
		min-width: 600px;
	}

	.el-table__body-wrapper {
	}

	.containertool .el-checkbox {
		display: block;
	}

	.containertool {
		background: #fff;
		min-width: 100px;
	}

	#bosxs {
		display: block;
		overflow: hidden;
	}

	#bosxs>* {
		float: left;
		margin-top: 10px;
	}

	#bosxs>p {
		float: right;
		font-size: 12px;
	}
</style>
<style scoped>
	.containertool {
		position: absolute;
		right: 10px;
		top: 10px;
		z-index: 10;
		padding: 10px;
		border-radius: 10px;
	}

	.tag {
		height: 40px;
		background-color: rgba(26, 35, 126, 1);
		margin-top: 10px;
	}

	.tag p {
		float: left;
		height: 100%;
		line-height: 40px;
		padding: 0 15px;
		text-align: center;
		border-right: 1px solid rgba(255, 255, 255, .5);
		color: #fff;
		font-size: 14px;
		cursor: pointer
	}

	.tag p.active {
		background-color: rgba(2, 167, 240, 1);
	}

	.query {
		overflow: hidden;
	}

	.query>ul {
		height: 50px;
		line-height: 50px;
		margin-top: 10px;
	}

	.query>ul li {
		/* width: calc(33.333% - 20px); */
		float: left;
		height: 50px;
		margin-right: 20px;
		font-size: 14px;
	}

	.query>ul li span {
		display: inline-block;
		width: 70px;
		margin-right: 10px;
		text-align: right;
	}

	.tool {
		height: 50px;
		background-color: rgba(242, 242, 242, 1);
	}

	.tool>* {
		float: left;
	}

	.tool>p {}

	.tool>p span {
		display: block;
		/* border-right:1px solid #ccc ; */
		height: 35px;
		margin-top: 7px;
		line-height: 35px;
		float: left;
		padding: 0 15px;
		font-size: 14px;
		color: #169BD5;
		cursor: pointer;
	}
</style>
